package com.adabank.controller;

import com.adabank.module.Login;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@RestController
@RequestMapping("/api")
//@RequiresAuthentication 登入了之后才能访问的注解
//@MapperScan("com/adabank/dao")
public class LogInController {
    HashMap<String, String> Session_username = new HashMap<>();


    @PostMapping("/login")
    public Controller<Object> login(@RequestBody Login login, HttpServletResponse httpServletResponse) {

//        System.out.println(login.getUsername());
//        System.out.println(login.getPassword());

        AuthenticationToken token = new UsernamePasswordToken(login.getUsername(), login.getPassword());
        Subject subject = SecurityUtils.getSubject();

        try {
            subject.login(token);
            Session_username.put("JSESSIONID", login.getUsername());
            return Controller.oof("OK", null, "YES");
        } catch (UnknownAccountException | IncorrectCredentialsException e) {
            return Controller.oof("ERROR", "密码错误", null);
        } //            密码错误
    }

    @RequiresAuthentication
    @GetMapping("/me")
    public Controller<String> isLogin(HttpServletRequest request) {
        for (Cookie cookie : request.getCookies()) {

            System.out.println(cookie.getName());

            if (cookie.getName().equals("JSESSIONID")) {
                return Controller.of(Session_username.get("JSESSIONID"));
            }
        }
        return Controller.oof("ERROR", "未登入", null);
    }


    @PostMapping("/logout")
    public Controller<String> logout(HttpServletResponse response) {
//        Cookie killMyCookie = new Cookie("userId", null);
//        killMyCookie.setMaxAge(0);
//        killMyCookie.setPath("/");
//        response.addCookie(killMyCookie);
//        使用shiro改造退出功能
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()) {
            subject.logout();
        }
        return Controller.of(null);
    }

}
